﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web.Mvc;

namespace CSF.Utility.Mvc
{
    public class SecureRoute : Route, IRouteWithArea
    {
        public SecureRoute(string url, IRouteHandler routeHandler, string area = "") :
            base(url, routeHandler)
        {
            _area = area;
        }

        public SecureRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler, string area = "") :
            base(url, defaults, routeHandler)
        {
            _area = area;
        }

        public SecureRoute(string url, RouteValueDictionary defaults,
            RouteValueDictionary constraints, IRouteHandler routeHandler, string area = "")
            : base(url, defaults, constraints, routeHandler)
        {
            _area = area;
        }

        public SecureRoute(string url, RouteValueDictionary defaults,
            RouteValueDictionary constraints, RouteValueDictionary dataTokens,
            IRouteHandler routeHandler, string area = "")
            : base(url, defaults, constraints, dataTokens, routeHandler)
        {
            _area = area;
        }

        public override RouteData GetRouteData(System.Web.HttpContextBase httpContext)
        {
            RouteData result = base.GetRouteData(httpContext);
            if (result != null)
            {
                var tokens = result.DataTokens;
                //if (!string.IsNullOrEmpty(httpContext.Request["SessionId"])
                //    && !tokens.ContainsKey("SessionId"))
                //{
                //    tokens.Add("SessionId", httpContext.Request["SessionId"]);
                //}
                if (_area != "" && !tokens.ContainsKey("area"))
                {
                    tokens.Add("area", _area);
                }
            }
            return result;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            var request = requestContext.HttpContext.Request;
            if (request.IsAuthenticated 
                && !string.IsNullOrEmpty(request["SessionId"])
                && !values.ContainsKey("SessionId"))
            {
                values.Add("SessionId", request["SessionId"]);
            }
            return base.GetVirtualPath(requestContext, values);
        }

        #region IRouteWithArea 成员

        private string _area = "";

        public string Area
        {
            get { return _area; }
        }

        #endregion
    }
}
